package org.zjvis.datascience.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.zjvis.datascience.common.widget.dto.WidgetFavouriteDTO;
import org.zjvis.datascience.common.exception.BaseErrorCode;
import org.zjvis.datascience.common.exception.DataScienceException;
import org.zjvis.datascience.common.util.JwtUtil;
import org.zjvis.datascience.service.mapper.WidgetFavouriteMapper;

/**
 * @description WidgetFavourite 可视化图表收藏服务 Service
 * @date 2021-12-26
 */
@Service
public class WidgetFavouriteService {

    @Autowired
    private WidgetFavouriteMapper widgetFavouriteMapper;

    public List<WidgetFavouriteDTO> query(long pipelineId) {
        long user = JwtUtil.getCurrentUserId();
        return widgetFavouriteMapper.select(pipelineId, user);
    }

    public void favourite(WidgetFavouriteDTO dto) {
        try {
            dto.setId(null);
            widgetFavouriteMapper.insertSelective(dto);
        } catch (DuplicateKeyException e) {
            throw new DataScienceException(BaseErrorCode.DUPLICATED_DATA);
        }
    }

    public void favouriteCancel(WidgetFavouriteDTO dto) {
        dto.setGmtCreator(JwtUtil.getCurrentUserId());
        widgetFavouriteMapper.delete(dto);
    }

    public int delete(Long id) {
        WidgetFavouriteDTO dto = widgetFavouriteMapper.selectByPrimaryKey(id);
        if (dto == null) {
            return 0;
        }
        if (dto.getGmtCreator() != JwtUtil.getCurrentUserId()) {
            throw DataScienceException.of(BaseErrorCode.UNAUTHORIZED, "需收藏本人操作");
        }
        return widgetFavouriteMapper.deleteByPrimaryKey(id);
    }

    public void deleteWidget(long widgetId) {
        widgetFavouriteMapper.delete(WidgetFavouriteDTO.builder().widgetId(widgetId).build());
    }

    public void deleteByPipelines(List<Long> pipelines) {
        widgetFavouriteMapper.deleteByPipelines(pipelines);
    }

}
